﻿package com.shootingGame
{
	import com.common.KeyStates;
	import com.common.utils.Math2;
	import com.shootingGame.physics.collisionReactionClasses.PlayerCollisionEffects;
	import com.shootingGame.physics.collisionReactionClasses.base.Colliders;
	import com.shootingGame.physics.collisionReactionClasses.base.CollisionEffects;
	import com.shootingGame.renderableClasses.AttachableObject;
	import com.shootingGame.renderableClasses.MobileObject;
	import com.shootingGame.weaponsClasses.Weapon;
	
	import flash.display.MovieClip;
	import flash.utils.getQualifiedSuperclassName;	
	
	public class Player extends MobileObject
	{		
		static public const MAXSPEED : Number = 0.3;
		//As a fraction of the max speed.
		static public var ACCELERATION:Number = 0.008;
		//As a fraction of the max speed.
		static public var DECELERATION:Number = ACCELERATION/3.0;
		
//		static public var STAMINA_RECOVERYRATE:int;
//		static public var STAMINA_DEPLETERATE:int;
//		static public var STAMINA_MAXDEFAULT:int;
		
//		private var timePassed:int;
//		static public var PLAYERSPEED_HORIZONTAL:Number;
//		static public var PLAYERSPEED_JUMPINITIAL:Number;
//		//Gravity. Encountered anomaly when trying Number less then 1.0
//		static public var GRAVITATION:int;
//		//When down key is pressed
//		
//		private var timer:Timer;
//		//FEAUTRE: Realistic Mode
// 		
//		public var realisticMode:Boolean;
//		public var maxStamina:int;
//		public var stamina:Number;
		///
		public var userName : String;
		public var keyStates : KeyStates;
		private var _weapon : Weapon;
		private var time_MouseDown : int;
		public var isPrimaryPlayer : Boolean;
		public var viewCone : MovieClip;
		public var darkRegion : MovieClip;
		
		public function Player(isPrimaryPlayer : Boolean, playerBlob:MovieClip, collisionEffects:CollisionEffects = null, xPos:Number = 0, yPos:Number = 0){
			super(playerBlob, xPos, yPos, MAXSPEED, ACCELERATION, DECELERATION);
			isToBeRendered = true;
			isToBeUpdated = true;
			this.isPrimaryPlayer = isPrimaryPlayer;
			canRegisterOrdinanceImpact = true;
			keyStates = new KeyStates();
			facing = 0;
			hitPoints = hitPointMax = 100;
			time_MouseDown = 0;
			GamePlayManager.instance.playerList.push(this);
			isViewAreaRenderOnly = false;
			if(collisionEffects)
				this.collisionEffects = collisionEffects;
			else
				this.collisionEffects = new PlayerCollisionEffects(this, Colliders.PLAYER);
			isExpired = true;
			//weapon = Weapons.FIST
			//FEAUTRE: Realistic Mode
//			stamina = maxStamina = Player.STAMINA_MAXDEFAULT;
		}
		
		//FEAUTRE: Realistic Mode
// 		public function timerTick(event:TimerEvent):void{
//			stamina+=Player.STAMINA_RECOVERYRATE;
//			if(stamina>maxStamina)
//				stamina = maxStamina;
//		}
		///
		
		/**
		 * Updates player position in temp x,y values.
		 */
		override public function update() : void{
			if(isPrimaryPlayer)
			{
				keyStates.MOUSE_X = GamePlayManager.instance.mouseX;
				keyStates.MOUSE_Y = GamePlayManager.instance.mouseY;
			}
			mouseLook();
			super.update();
			var firedBullets:Array;
			if(keyStates.MOUSELEFT_DOWN){
				time_MouseDown += 1;
				if(weapon){
					weapon.isTriggerDepressed = true;
					if(isPrimaryPlayer)
						firedBullets = attack_Primary(keyStates.MOUSE_X, keyStates.MOUSE_Y);
					else{
						//adjust target mouse coords to be relative to the non-primary player, who happens to be not at the centre of the screen.
						firedBullets = attack_Primary(keyStates.MOUSE_X + (memoryX - GamePlayManager.instance.player1.memoryX) - (memoryX - 400),
													keyStates.MOUSE_Y + (memoryY - GamePlayManager.instance.player1.memoryY) - (memoryY - 300));
					}
					if(firedBullets){
						while(firedBullets.length > 0){
							GamePlayManager.instance.ordinanceHolder.addChild(firedBullets.pop());
						}
					}
				}
			}
			else{
				if(weapon)
					weapon.isTriggerDepressed = false;
				time_MouseDown = 0;
			}
			
		}
		
		override public function render():void{
			super.render();
//			if(isPrimaryPlayer){
//				if(viewCone){
//					viewCone.rotation = facing;
//					viewCone.x = x;
//					viewCone.y = y;
////					if(darkRegion){
//////						darkRegion.rotation = facing;
//////						darkRegion.x = x;
//////						darkRegion.y = y;
////						var bmp:Bitmap;
////			            var bmdDark:BitmapData = new BitmapData(800,600);
////			            bmdDark.draw(new darkRegionBitmap());
////			            var bmdLight:BitmapData = new BitmapData(800,600);
////			            bmdLight.draw(new visibleRegionBitmap());
////			            var diffBmd:BitmapData = bmdDark.compare(bmdLight) as BitmapData;
////			            if(GamePlayManager.instance.darknessHolder.numChildren == 0){
////			            	bmp = new Bitmap(diffBmd, "auto", true);
////			            	GamePlayManager.instance.darknessHolder.addChild(bmp);
////			            }
////			            else{
////			            	bmp = GamePlayManager.instance.darknessHolder.getChildAt(0) as Bitmap;
////			            	bmp.bitmapData = diffBmd;
////			            }
////			            bmp.rotation = facing;
////			            
////					}
//				}
//			}
		}
		
				
		override protected function updateThrust():void{
			var tmp_ThrustX:Number = thrustX;
			var tmp_ThrustY:Number = thrustY;
			if(keyStates.UP){
				if(!keyStates.DOWN)
					tmp_ThrustY -= ACCELERATION;
			}
			else
				if(keyStates.DOWN){
					tmp_ThrustY += ACCELERATION;
				}
				else{
					if(thrustY > 0)
						tmp_ThrustY -= DECELERATION;
					else
						if(thrustY < 0)
							tmp_ThrustY += DECELERATION;
				}
			if(keyStates.LEFT){
				if(!keyStates.RIGHT)
					tmp_ThrustX -= ACCELERATION;
			}
			else
				if(keyStates.RIGHT){
					tmp_ThrustX += ACCELERATION;
				}
				else{
					if(thrustX > 0)
						tmp_ThrustX -= DECELERATION;
					else
						if(thrustX < 0)
							tmp_ThrustX += DECELERATION;
				}
			
			if(!keyStates.UP && !keyStates.DOWN){
				if(Math.abs(thrustY) < Math.abs(tmp_ThrustY))
					tmp_ThrustY = 0;
			}
			if(!keyStates.LEFT && !keyStates.RIGHT){
				if(Math.abs(thrustX) < Math.abs(tmp_ThrustX))
						tmp_ThrustX = 0;
			}
			thrustX = tmp_ThrustX;
			thrustY = tmp_ThrustY;
			
			
			if(thrustX > 1)
				thrustX = 1;
			else
				if(thrustX < -1)
					thrustX = -1;
			if(thrustY > 1)
				thrustY = 1;
			else
				if(thrustY < -1)
					thrustY = -1;
		}
		
		private function mouseLook() : void {
			if(isPrimaryPlayer)
				facing = Math2.getAngleOfElevationDegree(localToGlobal(preferredCentre).x, localToGlobal(preferredCentre).y, keyStates.MOUSE_X, keyStates.MOUSE_Y);
			else
				facing = Math2.getAngleOfElevationDegree(memoryX, memoryY, keyStates.MOUSE_X, keyStates.MOUSE_Y);
		}
		
		//Returns array of launched ordinance
		public function attack_Primary(targetX:Number, targetY:Number) : Array {
			return weapon.fire_Primary(targetX, targetY);
		}
		
		
		override public function addAttachment(attch:AttachableObject):void{
			if(flash.utils.getQualifiedSuperclassName(attch).search("Weapon") != 1)
				weapon = attch as Weapon;
			super.addAttachment(attch);
		}

		public function get weapon() : Weapon{
			return _weapon;
		}
		
		public function set weapon(value : Weapon) {
			if(_weapon)
				removeAttachment(_weapon);
			_weapon = value;
			if(_weapon)
				if(!_weapon.attachedTo == this)
					_weapon.attachedTo = this;
			
		}	
		
		override public function addObject_ToUpdateList():void
		{
			if(GamePlayManager.instance.playerList.indexOf(this) == -1)
				GamePlayManager.instance.playerList.push(this);
		}
		
		override public function removeObject_FromUpdateList() : void {
			var playerList : Array = GamePlayManager.instance.playerList;
			playerList.splice(playerList.indexOf(this),1);
		}
		
		override public function set isExpired(value:Boolean):void{
			if(_isExpired == value)
				return;
			_isExpired = value;
			visible = !value;
			isRenderingEnabled = !value;
			canRegisterOrdinanceImpact = !value;
			isHitDetectionEnabled = !value;
			if(isExpired){
				weapon = null;
				attachments = null;
			}
			else
				hitPoints = hitPointMax;
		}
		
		public function spawn() : Boolean {
            if (!isExpired)
                return false;
            isExpired = false;
            return true;
		}
		
					
		/**
		 * 
		 * 
		 */
		/* override public function collisionReactor(collidingObjects:Array):void{					
			for(var i:int=0; i<collidingObjects.length; i++){									
				if(collidingObjects[i].name=="ground"){
					if(tmpY >= collidingObjects[i].y - height){
					tmpY = collidingObjects[i].y -height;
					tmpVelocity.y=0;
					trace("hit?");
					}
				}
			}							
		} */
	}						
}
